<template>
  <view class="container">
    <!-- 标签栏 -->
    <view class="tab-bar-container" :class="{ 'featured': currentTab === 0 }">
      <scroll-view
        class="tab-bar"
        scroll-x="true"
        scroll-with-animation="true"
        :scroll-left="scrollLeft"
        show-scrollbar="false"
        enable-flex="true"
        scroll-anchoring="true"
      >
        <view class="tab-items">
          <view
            v-for="(tab, index) in tabs"
            :key="tab.id"
            class="tab-item"
            :class="{ active: currentTab === index }"
            @click="switchTab(index)"
          >
            <text class="tab-text">{{ tab.title }}</text>
          </view>
        </view>
      </scroll-view>

      <!-- 精选推荐卡片 -->
      <view
        class="featured-card"
        v-if="currentTab === 0 && products.length > 0"
      >
        <view class="featured-header">
          <view class="featured-title">精选推荐</view>
          <view class="featured-subtitle">精选美食，好吃不贵</view>
        </view>
        <view class="featured-products">
          <view
              class="product-item"
              v-for="(item, index) in products.slice(0, 3)"
              :key="index"
              @click="goToFoodDetail(getProductId(item))"
            >
            <image
              :src="getFeaturedProductImage(item)"
              class="product-image"
              mode="aspectFill"
            ></image>
            <view class="product-info">
              <text class="merchant-name">{{ getMerchantName(item) }}</text>
              <text class="product-name">{{
                getFeaturedProductTitle(item)
              }}</text>
              <view class="product-footer">
                <text class="product-price"
                  >￥{{ getFeaturedProductPrice(item) }}</text
                >
                <uni-icons type="right" size="16"></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="tab-content" :class="{ 'featured': currentTab === 0 }">
      <scroll-view scroll-y class="scroll-area">
        <!-- 精选推荐 -->
        <view v-if="currentTab === 0" class="tab-panel">
          <!-- 精选推荐卡片 -->
          <view
            class="featured-card"
            v-if="currentTab === 0 && products.length > 0"
          >
            <view class="featured-header">
              <view class="featured-title">精选推荐</view>
              <view class="featured-subtitle">精选美食，好吃不贵</view>
            </view>
            <view class="featured-products">
              <view
              class="product-item"
              v-for="(item, index) in products.slice(0, 3)"
              :key="index"
              @click="goToFoodDetail(getProductId(item))"
            >
                <image
                  :src="getFeaturedProductImage(item)"
                  class="product-image"
                  mode="aspectFill"
                ></image>
                <view class="product-info">
                  <text class="merchant-name">{{ getMerchantName(item) }}</text>
                  <text class="product-name">{{
                    getFeaturedProductTitle(item)
                  }}</text>
                  <view class="product-footer">
                    <text class="product-price"
                      >￥{{ getFeaturedProductPrice(item) }}</text
                    >
                    <uni-icons type="right" size="16"></uni-icons>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 排序和筛选控件 -->
          <view class="filter-controls">
            <view class="sort-dropdown">
              <view class="dropdown-selector">
                <text>综合排序</text>
                <uni-icons type="down" size="14"></uni-icons>
              </view>
            </view>
            <view class="filter-dropdown">
              <view class="dropdown-selector">
                <text>全部筛选</text>
                <uni-icons type="down" size="14"></uni-icons>
              </view>
            </view>
          </view>

          <!-- 店铺列表 -->
          <view class="content-section" v-if="shopList && shopList.length > 0">
            <view class="shop-list">
              <view
                    class="shop-item"
                    v-for="(shop, index) in shopList"
                    :key="shop.id || index"
                    @click="goToShopDetail(shop)"
                  >
                <image
                  :src="getShopImage(shop)"
                  class="shop-image"
                  mode="aspectFill"
                ></image>
                <view class="shop-info">
                  <view class="shop-header">
                    <text class="shop-name">{{ shop.title }}</text>
                    <text
                      :class="getBusinessStatusClass(shop)"
                      v-if="getBusinessStatus(shop) !== null"
                    >
                      {{ getBusinessStatus(shop) ? "营业中" : "已打烊" }}
                    </text>
                  </view>
                  <view class="shop-details">
                    <text class="score" style="color: #ff8d1a;">评分: {{ shop.score || "暂无" }}</text>
                    <text class="sales">月售: {{ shop.quantity || 0 }}</text>
                  </view>
                  <view class="shop-meta">
                    <text class="price">人均: ￥{{ shop.money || 0 }}</text>
                    <text class="time">{{
                      shop.reserve == 1 ? "接受预定" : "不接受预定"
                    }}</text>
                  </view>
                  <view class="shop-labels">
                    <text v-if="shop.label" class="label">{{
                      shop.label
                    }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          <!-- 添加空状态提示 -->
          <view class="content-section" v-else>
            <view class="empty-state">
              <text class="empty-text">暂无店铺信息</text>
            </view>
          </view>
        </view>

        <!-- 其他分类 -->
        <view
          v-for="(tab, tabIndex) in tabs.slice(1)"
          :key="tab.id"
          v-show="currentTab === tabIndex + 1"
          class="tab-panel"
        >
          <view class="content-section no-margin">
            <!-- 排序和筛选控件 -->
            <view class="filter-controls compact">
              <view class="sort-dropdown">
                <view class="dropdown-selector">
                  <text>综合排序</text>
                  <uni-icons type="down" size="14"></uni-icons>
                </view>
              </view>
              <view class="filter-dropdown">
                <view class="dropdown-selector">
                  <text>全部筛选</text>
                  <uni-icons type="down" size="14"></uni-icons>
                </view>
              </view>
            </view>
            
            <!-- 店铺列表 -->
            <view class="content-section" v-if="shopList && shopList.length > 0">
              <view class="shop-list">
                <view
                  class="shop-item"
                  v-for="(shop, index) in shopList"
                  :key="shop.id || index"
                  @click="goToShopDetail(shop)"
                >
                  <image
                    :src="getShopImage(shop)"
                    class="shop-image"
                    mode="aspectFill"
                  ></image>
                  <view class="shop-info">
                    <view class="shop-header">
                      <text class="shop-name">{{ shop.title }}</text>
                      <text
                        :class="getBusinessStatusClass(shop)"
                        v-if="getBusinessStatus(shop) !== null"
                      >
                        {{ getBusinessStatus(shop) ? "营业中" : "已打烊" }}
                      </text>
                    </view>
                    <view class="shop-details">
                      <text class="score" style="color: #ff8d1a;">评分: {{ shop.score || "暂无" }}</text>
                      <text class="sales">月售: {{ shop.quantity || 0 }}</text>
                    </view>
                    <view class="shop-meta">
                      <text class="price">人均: ￥{{ shop.money || 0 }}</text>
                      <text class="time">{{
                        shop.reserve == 1 ? "接受预定" : "不接受预定"
                      }}</text>
                    </view>
                    <view class="shop-labels">
                      <text v-if="shop.label" class="label">{{
                        shop.label
                      }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <!-- 当前分类下没有店铺时显示 -->
            <view
              v-else
              class="empty-state"
            >
              <text class="empty-text">该分类下暂无店铺</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import { foodAPI } from '../../static/indexAPI.js';
import config from "@/static/config.js";
	export default {
	data() {
    return {
      currentTab: 0,
      tabs: [{ id: 0, title: "精选" }], // 初始化精选标签
      products: [], // 推荐美食
      shopList: [], // 店铺列表
      allShops: [], // 所有店铺
      scrollLeft: 0, // 横向滚动位置
    };
  },

  onLoad() {
    this.fetchFoodData();
    // 页面加载完成后隐藏滚动条
    this.$nextTick(() => {
      this.scrollLeft = 0;
    });
  },

  methods: {
    switchTab(index) {
      this.currentTab = index;
      this.scrollLeft = 0;
      // 如果是精选页，恢复所有店铺列表
      if (index === 0) {
        this.shopList = this.allShops.slice(); // 恢复完整店铺列表
      } 
      // 如果不是精选页，则根据分类ID获取店铺列表
      else if (index > 0 && this.tabs[index]) {
        this.fetchShopsByType(this.tabs[index].id);
      }
    },

    
    // 获取商品ID
    getProductId(item) {
      // 判断是否存在food数据，如果存在则使用food中的商品id，否则使用外层id
      if (item.food && item.food.id) {
        return item.food.id;
      } else if (item.id) {
        return item.id;
      }
      return null;
    },
    
    // 跳转到食品详情页
    goToFoodDetail(id) {
      if (id) {
        uni.navigateTo({
          url: '/pages/foodDetail/foodDetail?id=' + id
        });
      } else {
        uni.showToast({
          title: '商品信息有误',
          icon: 'none'
        });
      }
    },

    scrollToTab(index) {
      // 使用nextTick确保DOM更新完成后再执行
      this.$nextTick(() => {
        // 获取tab容器节点
        const tabBarQuery = uni
          .createSelectorQuery()
          .in(this)
          .select(".tab-bar");

        tabBarQuery
          .scrollOffset((scrollRes) => {
            if (!scrollRes) return;

            // 获取所有tab项
            uni
              .createSelectorQuery()
              .in(this)
              .selectAll(".tab-item")
              .boundingClientRect((itemRects) => {
                if (!itemRects || !itemRects[index]) return;

                // 获取容器信息
                uni
                  .createSelectorQuery()
                  .in(this)
                  .select(".tab-bar")
                  .boundingClientRect((containerRes) => {
                    if (!containerRes) return;

                    const containerWidth = containerRes.width;
                    const scrollLeft = scrollRes.scrollLeft;
                    const targetItem = itemRects[index];

                    // 计算目标项在容器中的位置
                    const itemLeft =
                      targetItem.left - containerRes.left + scrollLeft;
                    const itemRight = itemLeft + targetItem.width;

                    // 判断目标项是否在可视区域内
                    if (itemLeft < scrollLeft) {
                      // 目标项在可视区域左侧，需要向左滚动
                      this.scrollLeft = itemLeft;
                    } else if (itemRight > scrollLeft + containerWidth) {
                      // 目标项在可视区域右侧，需要向右滚动
                      this.scrollLeft = itemRight - containerWidth;
                    } else {
                      // 目标项已经在可视区域内，不需要滚动
                      // 但为了保持一致性，仍然将其居中
                      const centerPosition =
                        itemLeft - (containerWidth - targetItem.width) / 2;
                      this.scrollLeft = Math.max(0, centerPosition);
                    }
                  })
                  .exec();
              })
              .exec();
          })
          .exec();
      });
    },

    // 获取美食页面数据
      fetchFoodData() {
        foodAPI.getFoodData().then((res) => {
          // 打印详细数据结构
          if (res.data.code === 1) {
            const data = res.data.data;
            if (data.tabs) {
              console.log("tabs分类数据:", data.tabs);
            }
            if (data.products) {
              console.log("推荐美食数据:", data.products);
            }
            if (data.list) {
              console.log("店铺列表数据:", data.list);
            }

            // 设置推荐美食
            this.products = Array.isArray(data.products) ? data.products : [];

            // 设置店铺列表 - 从接口的list字段获取数据
            // 如果list是对象，则转换为数组
            if (
              data.list &&
              typeof data.list === "object" &&
              !Array.isArray(data.list)
            ) {
              this.shopList = Object.values(data.list);
              this.allShops = Object.values(data.list);
            } else {
              this.shopList = Array.isArray(data.list) ? data.list : [];
              this.allShops = Array.isArray(data.list) ? data.list : [];
            }


            // 设置标签（分类）
            if (data.tabs && Array.isArray(data.tabs)) {
              // 移除tabs中的"精选"项，因为我们已经有一个固定的"精选"标签
              const filteredTabs = data.tabs.filter(
                (tab) => tab.title !== "精选"
              );
              // 将"精选"放在第一位，后面跟其他分类
              this.tabs = [{ id: 0, title: "精选" }, ...filteredTabs];
            }
          } else {
            uni.showToast({
              title: res.data.msg || "获取数据失败",
              icon: "none",
            });
          }
        }).catch((err) => {
          console.error("请求美食数据失败:", err);
          uni.showToast({
            title: "网络请求失败",
            icon: "none",
          });
        });
      },

      // 根据店铺类型ID获取店铺列表
      fetchShopsByType(typeId) {
        uni.showLoading({
          title: '加载中...'
        });
        
        foodAPI.getShopsByType({
          foodtype_id: typeId
        }).then((res) => {
          uni.hideLoading();
          
          if (res.data.code === 1) {
            // 根据实际返回的数据结构调整处理方式
            let rawData = [];
            if (Array.isArray(res.data.data)) {
              // 直接使用返回的数组数据
              rawData = res.data.data;
            } else if (res.data.data && res.data.data.list && Array.isArray(res.data.data.list)) {
              // 如果是包含list属性的对象
              rawData = res.data.data.list;
            }
            
            // 根据foodtype_id过滤数据
            this.shopList = rawData.filter(shop => {
              if (shop.foodtype_id) {
                // 处理单个ID或多个ID的情况
                const ids = shop.foodtype_id.toString().split(',');
                return ids.includes(typeId.toString());
              }
              return false;
            });
          } else {
            uni.showToast({
              title: res.data.msg || '获取数据失败',
              icon: 'none'
            });
            this.shopList = [];
          }
        }).catch((err) => {
          uni.hideLoading();
          console.error("请求店铺数据失败:", err);
          uni.showToast({
            title: "网络请求失败",
            icon: "none",
          });
          this.shopList = [];
        });
      },

    getProductImage(product) {
      if (product.img) {
        return product.img.startsWith("http")
          ? product.img
          : config.baseURL + product.img;
      }
      return config.imgUrl + "/img/icons1.png";
    },

    getShopImage(shop) {
      if (shop.img) {
        return shop.img.startsWith("http")
          ? shop.img
          : config.baseURL + shop.img;
      }
      return config.imgUrl + "/img/icons1.png";
    },

    getFeaturedProductImage(item) {
      // 检查是否有food数据且有图片
      if (item.food && item.food.img) {
        return item.food.img.startsWith("http")
          ? item.food.img
          : config.im + item.food.img;
      }
      // 返回默认图片
      return config.imgUrl + "/img/eat.png";
    },
    getMerchantName(item) {
      // 获取商家名称
      if (item.merchant && item.merchant.name) {
        return item.merchant.name;
      }
      if (item.shop && item.shop.title) {
        return item.shop.title;
      }
      if (item.title) {
        return item.title;
      }
      return "未知商家";
    },

    getBusinessStatus(shop) {
      // 获取当前时间
      const now = new Date();
      const currentTime = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds(); // 格式化为HHMMSS
      
      // 获取开店和关店时间
      let startTime = shop.starttime || '00:00:00';
      let endTime = shop.endtime || shop.end || '23:59:59';
      
      // 确保时间格式统一为 HH:MM:SS
      if (startTime.length <= 5) { // 如果是 HH:MM 格式，补充秒数
        startTime += ':00';
      }
      
      if (endTime.length <= 5) { // 如果是 HH:MM 格式，补充秒数
        endTime += ':00';
      }
      
      // 解析开店时间
      const [startHour, startMinute, startSecond] = startTime.split(':').map(Number);
      const start = startHour * 3600 + startMinute * 60 + startSecond;
      
      // 解析关店时间
      const [endHour, endMinute, endSecond] = endTime.split(':').map(Number);
      const end = endHour * 3600 + endMinute * 60 + endSecond;
      
      // 处理跨天情况（如营业到凌晨）
      if (end < start) {
        // 跨天营业，如从晚上到凌晨
        return currentTime >= start || currentTime <= end;
      }
      
      // 不跨天的正常情况
      return currentTime >= start && currentTime <= end;
    },

    goToShopDetail(shop) {
      // 将店铺信息存储到本地
      try {
        uni.setStorageSync('currentShop', shop);
        console.log('店铺信息已存储到本地:', shop);
      } catch (e) {
        console.error('存储店铺信息失败:', e);
      }
      
      // 跳转到店铺详情页面，不再传递参数
      uni.navigateTo({
        url: '/pages/shop/shop'
      });
    },

    getBusinessStatusClass(shop) {
      const isOpen = this.getBusinessStatus(shop);
      if (isOpen === null) return "";
      return isOpen ? "business-open" : "business-closed";
    },

    getFeaturedProductTitle(item) {
      // 优先使用food的标题
      if (item.food && item.food.title) {
        return item.food.title;
      }
      // 否则使用产品的标题
      return item.title || "未知商品";
    },

    getFeaturedProductPrice(item) {
      // 优先使用food的价格
      if (item.food && item.food.price) {
        return item.food.price;
      }
      // 返回默认价格
      return "0";
    },
    getShopsByType(typeId) {
      // 确保 allShops 是数组
      if (!Array.isArray(this.allShops)) {
        console.warn("allShops is not an array:", this.allShops);
        return [];
      }

      return this.allShops.filter((shop) => {
        // 确保 shop 和 foodtype_id 存在
        if (!shop || shop.foodtype_id === undefined) {
          return false;
        }
        return parseInt(shop.foodtype_id) === parseInt(typeId);
      });
    },
  },
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f4f4f4;
}

.tab-bar-container {
  position: relative;
  background-color: #f7bd2c; /* 与顶部导航栏相同的背景色 */
}

.tab-bar-container.featured {
  padding-bottom: 60px; /* 精选页的底部空白区域 */
}
.tab-bar {
  white-space: nowrap;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 0px 0 15px 0;
  position: relative;
  /* 隐藏滚动条 */
  -ms-overflow-style: none; /* IE 和 Edge */
  scrollbar-width: none; /* Firefox */
  /* 防止页面加载时出现滚动条闪烁 */
  overflow: hidden;
}

/* 隐藏 Webkit 浏览器的滚动条 */
.tab-bar::-webkit-scrollbar {
  display: none;
  width: 0 !important;
  height: 0 !important;
}

.tab-items {
  display: flex;
  width: 100%;
}

.tab-item {
  flex: 1;
  padding: 10px 10px;
  font-size: 16px;
  color: rgba(255, 255, 255, 0.8);
  text-align: center;
  box-sizing: border-box;
}

.tab-item.active {
  color: #fff;
  font-weight: bold;
}

/* 精选推荐卡片 */
.featured-card {
  position: absolute;
  top: 120%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 88%;
  background-color: #fff;
  border-radius: 15px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 15px;
  z-index: 10;
}

.featured-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.featured-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.featured-subtitle {
  font-size: 14px;
  color: #444444;
}
.featured-products {
  display: flex;
  justify-content: space-between;
}

.product-item {
  /* flex: 1; */
  display: flex;
  flex-direction: column;
  align-items: center;
  /* margin: 0 5px;
  width: 100px; */
  height: 250rpx;
}

.product-image {
  width: 90px;
  height: 90px;
  border-radius: 8px;
  margin-bottom: 8px;
}

.product-info {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.merchant-name {
  font-size: 12px;
  color: #666;
  /* text-align: center ; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  margin-bottom: 4px;
}

.product-name {
  font-size: 13px;
  color: #333;
  /* text-align: center ; */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  margin-bottom: 4px;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.product-price {
  font-size: 14px;
  color: red;
}

.arrow {
  font-size: 16px;
  color: #ccc;
}

.tab-content {
  flex: 1;
  overflow: hidden;
}

.tab-content.featured {
  margin-top: 120px; /* 精选页的顶部边距 */
}

.scroll-area {
  height: 100%;
}

/* 排序和筛选控件样式 */
.filter-controls {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
  position: sticky;
  top: 0;
  z-index: 9;
  background-color: #f4f4f4;
}

.sort-dropdown,
.filter-dropdown {
  flex: 0.4;
  margin: 0 5px;
}

.dropdown-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 15px;
  background-color: #fff;
  font-size: 14px;
  color: #333;
}

.content-section {
  padding: 4px 10px;
}
.content-section.no-margin {
  padding: 0 10px;
}

.filter-controls.compact {
  padding: 5px 15px; /* 减小内边距 */
  margin-top: 0; /* 移除外边距 */
}

/* 优化店铺列表渲染 */
.shop-list {
  transform: translateZ(0); /* 启用硬件加速 */
  will-change: transform; /* 提示浏览器该元素将要发生变换 */
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  display: block;
}

/* 食物项样式 */
.food-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.food-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  margin-right: 10px;
}

.food-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.food-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.food-description {
  font-size: 13px;
  color: #999;
  margin: 5px 0;
}

.food-price-row {
  display: flex;
  align-items: center;
}

.food-price {
  font-size: 18px;
  color: #ff8d1a;
  font-weight: bold;
}

/* 店铺项样式 */
.shop-item {
  display: flex;
  background: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.shop-image {
  width: 100px;
  height: 100px;
  border-radius: 6px;
  margin-right: 10px;
}

.shop-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.shop-header {
  display: flex;
  flex-direction: column;
}

.shop-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.business-open,
.business-closed {
  align-self: flex-start;
  font-size: 12px;
  color: #43cf7c;
  border: 1px solid #43cf7c;
  background-color: #fff;
  padding: 1px 4px;
  border-radius: 3px;
  margin-bottom: 5px;
  width: fit-content;
}

.business-closed {
  color: #999;
  border-color: #999;
}

.shop-details {
  display: flex;
  gap: 15px;
  margin-bottom: 5px;
}

.score,
.sales {
  font-size: 13px;
  color: #666;
}

.shop-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.price,
.time {
  font-size: 13px;
  color: #666;
}

.shop-labels {
  margin-bottom: 5px;
}

.label {
  font-size: 12px;
  color: #f7bd2c;
  background-color: #fff9ef;
  padding: 2px 5px;
  border-radius: 3px;
  margin-right: 5px;
}

.shop-reserve {
  font-size: 12px;
}

.reserve-yes {
  color: #07c160;
}

.reserve-no {
  color: #999;
}

.empty-state {
  text-align: center;
  padding: 50px 0;
}

.empty-text {
  font-size: 16px;
  color: #999;
}
</style>